package com.hoshiicloud.user.controller.usercenter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.usercenter.MemberBankcard;
import com.hoshiicloud.user.param.usercenter.MemberBankcardPageParam;
import com.hoshiicloud.user.param.usercenter.MemberBankcardUpdateParam;
import com.hoshiicloud.user.service.usercenter.IMemberBankcardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户银行卡Controller类
 *
 * @author : yangcheng
 * @date : 2019/5/11 16:47
 * @mail : maiboyc@163.com
 **/
@RestController
@RequestMapping("/memberBankcard")
@Api(value = "用户银行卡管理", tags = {"用户银行卡操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class MemberBankcardController extends BaseController {

    // 用户银行卡Service
    @Autowired
    private IMemberBankcardService memberBankcardService;

    /**
     * 根据ID查询用户银行卡
     * @param id ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询用户银行卡信息", consumes = MediaType.ALL_VALUE)
    public Response<MemberBankcard> getById(@PathVariable("id") Long id) {
        Response rs;
        try {
            rs = Response.data(memberBankcardService.getById(id));
        } catch (Exception e) {
            logger.error("根据ID查询用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID组查询用户银行卡
     * @param ids ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询用户银行卡信息", consumes = MediaType.ALL_VALUE)
    public Response<List<MemberBankcard>> getByIds(@RequestParam("ids") List<Long> ids) {
        Response<List<MemberBankcard>> rs;
        try {
            rs = Response.data(memberBankcardService.getByIds(ids));
        } catch (Exception e) {
            logger.error("根据ID组查询用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据持卡人查询用户银行卡
     * @param name  持卡人
     * @return Response
     */
    @GetMapping("/find/{name}")
    @ApiOperation(value = "根据持卡人查询", notes = "根据持卡人查询用户银行卡信息", consumes = MediaType.ALL_VALUE)
    public Response<IPage<MemberBankcard>> findByName(@PathVariable("name") String name) {
        Response<IPage<MemberBankcard>> rs;
        try {
            MemberBankcard entity = new MemberBankcard();
            entity.setBankAccountname(name);
            rs = Response.data(memberBankcardService.List(entity));
        } catch (Exception e) {
            logger.error("根据持卡人查询用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户银行卡（get请求，以具体值接收参数）
     * @param pageIndex         当前页码
     * @param pageSize          每页显示的记录数
     * @param userId            用户主键ID
     * @param bankName          银行名称
     * @param bankAccountname   持卡人
     * @param bankAccount       卡号
     * @param bankAddress       所在支行
     * @return Response
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户银行卡信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", required = true, dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "Long", example = "10", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户主键ID", dataType = "Long", example = "123", paramType = "query"),
            @ApiImplicitParam(name = "bankName", value = "银行名称", dataType = "String", example = "XX银行", paramType = "query"),
            @ApiImplicitParam(name = "bankAccountname", value = "持卡人", dataType = "String", example = "XX", paramType = "query"),
            @ApiImplicitParam(name = "bankAccount", value = "卡号", dataType = "String", example = "123456789789165", paramType = "query"),
            @ApiImplicitParam(name = "bankAddress", value = "所在支行", dataType = "String", example = "XX支行", paramType = "query")
    })
    public Response<IPage<MemberBankcard>> list(Long pageIndex, Long pageSize, Long userId, String bankName, String bankAccountname, String bankAccount, String bankAddress) {
        Response<IPage<MemberBankcard>> rs;
        try {
            MemberBankcard entity = new MemberBankcard();
            entity.setPageIndex(pageIndex);
            entity.setPageSize(pageSize);
            entity.setUserId(userId);
            entity.setBankName(bankName);
            entity.setBankAccountname(bankAccountname);
            entity.setBankAccount(bankAccount);
            entity.setBankAddress(bankAddress);
            rs = Response.data(memberBankcardService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户银行卡（post请求，以对象接收参数）
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户银行卡信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<IPage<MemberBankcard>> list(@RequestBody MemberBankcardPageParam param) {
        Response<IPage<MemberBankcard>> rs;
        try {
            MemberBankcard entity = new MemberBankcard();
            BeanUtils.copyProperties(param, entity);
            rs = Response.data(memberBankcardService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 新增用户银行卡
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增用户银行卡", notes = "新增用户银行卡信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Valid MemberBankcard entity, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                rs = Response.data(memberBankcardService.insert(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("新增用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        }catch (Exception e) {
            logger.error("新增用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 修改用户银行卡
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改用户银行卡", notes = "修改用户银行卡信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Valid MemberBankcardUpdateParam param, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                MemberBankcard entity = new MemberBankcard();
                BeanUtils.copyProperties(param, entity);
                rs = Response.data(memberBankcardService.update(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("更新用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("更新用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID删除用户银行卡
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除用户银行卡信息", consumes = MediaType.ALL_VALUE)
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        Response<Boolean> rs;
        try {
            rs = Response.data(memberBankcardService.delete(id));
        } catch (ServiceException e) {
            logger.error("删除用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("删除用户银行卡信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

}  